package mywork

import akka.actor.{ActorSystem, PoisonPill, Props}
import akka.cluster.singleton.{ClusterSingletonManager, ClusterSingletonManagerSettings}
import com.typesafe.config.ConfigFactory

/**
  * Created by shichen on 2017/8/1.
  */
object MyMain {
  //先启动backend，再启动frontend，worker最后
  def main(args: Array[String]): Unit = {
    if (args.isEmpty) {
      println("args empty")
      sys.exit(-1)
    }else {
      val port = args(0).toInt
      if (2000 <= port && port <= 2999)
        startMasterSingle(port,"backend")
      else if (3000 <= port && port <= 3999)
        startFrontend(port)
      else
        startWorker()
    }
  }

  def startMasterSingle(port: Int,role: String): Unit = {
    val conf = ConfigFactory
      .parseString(s"akka.cluster.roles=[$role]")
      .withFallback(ConfigFactory.parseString("akka.remote.netty.tcp.port=" + port))
      .withFallback(ConfigFactory.load())
    val sys = ActorSystem("ClusterSystem",conf)

    //create singleton manager
    sys.actorOf(ClusterSingletonManager.props(
      Props(new MyMaster),
      PoisonPill,
      ClusterSingletonManagerSettings(sys).withRole(role)
    ),"master")
  }

  def startFrontend(port: Int): Unit = {
    val conf = ConfigFactory
      .parseString("akka.remote.netty.tcp.port=" + port)
      .withFallback(ConfigFactory.load())
    val sys = ActorSystem("ClusterSystem",conf)

    val frontend = sys.actorOf(Props[MyFrontend],"myfrontend")
    sys.actorOf(Props(classOf[MyProducer],frontend),"myproducer")
  }

  def startWorker(): Unit = {

  }
}
